<?php

class Receive
{
    // 广东那边需要定义的接口文件命名规范
    private static $type = [
        'BASIC' => [
            'PTJB', 'PTYYGM', 'PTZF', 'PTFWJG', 'CPTJYXK', 'PTYJ', 'CLJB', 'CLBX', 'CLLC', 'JSYJB', 'JSYPX', 'JSYYDZD',
            'JSYTJ', 'CKJB', 'CKZT', 'PTTZR', 'PTLXR', 'GTJSYHT', 'PTQYJR'
        ],
        'OPERATION' => [
            'CLYYSX', 'CLYYXX', 'YYCF', 'YYDD', 'YYZF'
        ],
        'GPS' => [
            'JSYDW', 'CKDW'
        ],
        'ORDER' => [
            'DDFQ', 'DDCG', 'DDCX', 'DDBCQQ', 'DDBC', 'DDWY', 'JSYSB', 'JSYXB'
        ],
        'EVALUATE' => [
            'CKPJ', 'CKTSCL', 'JSYCF', 'JSYCF', 'JSYXY'
        ],
        'RELATIONSHIP' => [
            'RCDYGX'
        ],
        'SHARE' => [
            'SRXKCHCCF', 'SRXKCHCDD'
        ],
        'TOKEN' => [
            'ACCESS'
        ]
    ];

    private static $total = 0;


    public static function create($dir, $file)
    {
        // 自动载入
        // 设置超时时间
        @ini_set('output_buffering', 'Off');
        @ini_set('zlib.output_compression', 0);
        // 当你的页面有大量数据时，建议使用set_time_limit()来控制运行时间
        set_time_limit(5 * 60);
        ini_set('memory_limit', '-1');

        ob_implicit_flush(true);

        $objPHPExcel = PHPExcel_IOFactory::load($file);
        $sheets = $objPHPExcel->getAllSheets();
        foreach ($sheets as $objWorksheet) {
            $title = $objWorksheet->getTitle();
            // 判断是否已经存在过文件，有就删除
            $handle = opendir($dir);
            while (false !== $file = (readdir($handle))) {
                if ($file != '.' && $file != '..') {
                    $far = explode('_', $file);
                    if (in_array($title, $far)) {
                        unlink(realpath($dir . '/' . $file));
                    }
                }
            }
            closedir($handle);
            // 只能由大写英文字母组成
            if (preg_match('/^[A-Z]+$/', $title, $matches)) {
                echo "\n$title-----------";
                // 获取行数
                $highestRow = $objWorksheet->getHighestRow();
                // 最高列的英文字母
                $highestColumn = $objWorksheet->getHighestColumn();
                // 有多少列
                $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
                // 获取字段名称
                $fieldTitles = [];
                $row = 3;
                for ($col = 0; $col < $highestColumnIndex; $col++) {
                    $keys = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                    if ($keys == "success" || $keys == "reason") {
                        continue;
                    }
                    if ($objWorksheet->getCellByColumnAndRow($col, $row)->getValue()) {
                        $fieldTitles[$col] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                    } else {
                        continue;
                    }
                }

                // 从第四行开始读取数据
                $listCount = count($fieldTitles);
                $recordCount = 0;
                $fieldValues = [];
                $records = $record = $json = [];

                for ($row = 4; $row <= $highestRow; $row++) {
                    // 字段值
                    for ($col = 0; $col < $listCount; $col++) {
                        $fieldValues[$col] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                    }
                    //
                    if (!implode('', $fieldValues)) {
                        continue;
                    }
                    // 从新组装数据
                    $records[] = array_combine($fieldTitles, $fieldValues);
                    $recordCount++;
                }

                if ($title == 'ACCESS') {
                    $json = $records[0];
                } else {
                    $json['items'] = $records;
                }

                self::$total++;
                // 文件命名
                $file_name_req = '';
                foreach (self::$type as $key => $item) {
                    if (in_array($matches[0], $item)) {
                        //  $file_name_res = 'syjcx_BASIC_' . $matches[0] . '_RES_' . date('YmdHisB') . '.json';
                        $file_name_req = 'syjcx_' . $key . '_' . $matches[0] . '_REQ_' . date('YmdHisB') . '.json';
                        echo $file_name_req . "\n";
                    }
                }
                file_put_contents(APP_ROOT . '/tmp/' . $file_name_req, json_encode($json, true));
            }
        }

        echo "\ntotal: ", self::$total;
    }
}

if (!isset($argv[1])) {
    exit('run like this: php ' . basename(__FILE__) . ' 缺少Excel文件 {json_string} | xls file');
}
// 定义文件路径
define('APP_ROOT', __DIR__);
// 获取传送Excel文件名
$msg = $argv[1];
// 引入配置文件
$config = include APP_ROOT . '/../config/config.php';

if (is_file($msg)) {
    $dir = APP_ROOT . "/tmp";
    include APP_ROOT . '/../vendor/autoload.php';
    $file = $msg;
    Receive::create($dir, $file);
} else {
    echo "文件错误";
}